﻿using Letter.IO.Scheduler;
using System.Buffers;
using ePipe;
using System.Threading;

namespace Letter.Net;

public sealed class ChannelSettingsAllotter : IChannelSettingsAllotter
{
    public ChannelSettingsAllotter(MemoryPool<byte> memoryPool, long  maxReadBufferSize, long maxWriteBufferSize)
    {
        this.MemoryPool = memoryPool;
        this.MaxReadBufferSize = maxReadBufferSize;
        this.MaxWriteBufferSize = maxWriteBufferSize;
    }

    private MemoryPool<byte> MemoryPool
    {
        get;
        set;
    }

    private long MaxReadBufferSize
    {
        get;
        set;
    }

    private long MaxWriteBufferSize
    {
        get;
        set;
    }

    public IChannelSettings Next()
    {
        var applicationScheduler = PipeScheduler.ThreadPool;
        var transportScheduler = SchedulerUtil.SelectSocketsScheduler();
        return ChannelSettingsProvider.CreateSettings
        (
            transportScheduler,
            new PipeOptions<byte>(this.MemoryPool, applicationScheduler, transportScheduler, this.MaxReadBufferSize, this.MaxReadBufferSize / 2, useSynchronizationContext: false),
            new PipeOptions<byte>(this.MemoryPool, transportScheduler, applicationScheduler, this.MaxWriteBufferSize, this.MaxWriteBufferSize / 2, useSynchronizationContext: false),
            this.MemoryPool
        );
    }
}